package cn.ly.link.two;

public class TwoLinkList<E> {
	private Node2 first;
	private Node2 last;
	
	public TwoLinkList(){
		this.first = null;
		this.last = null;
	}
	
	public boolean isEmpty(){
		return first == null;
	}
	
	public void insertFirst(E e){
		Node2 newNode = new Node2(e);
		if(isEmpty()){
			last = newNode;
		}else{
			first.pre = newNode;
			newNode.next = first;
		}
		first = newNode;
	}
	
	public void insertLast(E e){
		Node2 newNode = new Node2(e);
		if(isEmpty()){
			first = newNode;
		}else{
			last.next = newNode;
			newNode.pre = last;
		}
		last = newNode;
	}
	
	public E removeFirst(){
		Node2 temp = first;
		if(first.next == null){
			last = null;
		}else{
			first.next.pre = null;
		}
		first = first.next;
		return (E)temp.data;
	}
	
	public E removeLast(){
		Node2 temp = last;
		if(first.next == null){
			first = null;
		}else{
			last.pre.next = null;
		}
		last = last.pre;
		return (E)temp.data;
	}
	
	public boolean insertAfter(E e1,E e2){
		Node2 newNode = new Node2(e2);
		Node2 cur = first;
		while(cur.data != e1){
			cur = cur.next;
			if(cur == null){
				return false;//查找指定元素失败，退出，不插入
			}
		}
		if(cur == last){
			last = newNode;
		}else{
			cur.next.pre = newNode;
		}
		newNode.next = cur.next;
		newNode.pre = cur;
		cur.next = newNode;
		return true;
	}
	
	public E removeKey(E e){
		Node2 cur = first;
		while(cur.data != e){
			cur = cur.next;
		}
		if(cur == null){
			return null;
		}else{
			if(cur == first){
				cur.next.pre = null;
				first = cur.next;
			}else if(cur == last){
				cur.next.next = null;
				last = cur.pre;
			}else{
				cur.pre.next = cur.next;
				cur.next.pre = cur.pre;
			}
		}
		return (E)cur.data;
	}
	
	public void displayForward(){
		Node2 cur = first;
		while(cur != null){
			cur.display();
			cur = cur.next;
		}
		System.out.println();
	}
	
	public void displayBackward(){
		Node2 cur = last;
		while(cur != null){
			cur.display();
			cur = cur.pre;
		}
		System.out.println();
	}
	
	

}
